<?php 
$orderIds = $this->getRequest()->getPost('order_ids');
$_coreHelper = $this->helper('core');
$startDate = $this->getRequest()->getParam('start_date','');
$endDate = $this->getRequest()->getParam('end_date','');

$session = Mage::getSingleton('admin/session');
$roleId = $session->getUser()->getRoleId();
$roles = Mage::helper('zgb')->getUserRoles();
$zgb = Mage::helper('zgb');
$ids = array(0);
$storeIds = array(0);

$items = array();
$resource = Mage::getSingleton('core/resource');
$db = $resource->getConnection('core_read');

if($zgb->getRoleId('manufacturer') == $roleId)
{
	$manufacturer = Mage::getModel('zgb/manufacturer')->loadByAdminId($session->getUser()->getId());
	$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToFilter('manufacturer_id', array('eq'=>$manufacturer->getId()));
	foreach($products as $product)
	{
		if(!in_array($product->getId(),$ids))
		{
			$ids[] = $product->getId();
		}
	}

	$sql = "select product_id,name,sum(qty_ordered) as qty from sales_flat_order_item as item left join sales_flat_order as o on item.order_id=o.entity_id  where 1=1 ";

	if($ids && $roleId != 1)
	{
		$sql .= " and item.product_id in (".implode(',',$ids).")";
	}
}else if($zgb->getRoleId('dealer') == $roleId){
	// $dealer = Mage::getModel('zgb/dealer')->loadByAdminId($session->getUser()->getId());
	// $resource = Mage::getSingleton('core/resource');
	// $db = $resource->getConnection('core_read');
	// $sql = "SELECT distinct(entity_id) FROM `catalog_product_entity_int` WHERE attribute_id=138 AND `value`={$dealer->getId()}";
	// $query = $db->query($sql);
	// $products = $query->fetchAll();

	// foreach($products as $product)
	// {
	// 	if(!in_array($product['entity_id'],$ids))
	// 	{
	// 		$ids[] = $product['entity_id'];
	// 	}
	// }

	// $sql = "SELECT distinct(store_id) FROM `catalog_product_entity_int` WHERE attribute_id=138 AND `value`={$dealer->getId()}";
	// $query = $db->query($sql);
	// $stores = $query->fetchAll();

	// foreach($stores as $store)
	// {
	// 	if(!in_array($store['store_id'],$storeIds))
	// 	{
	// 		$storeIds[] = $store['store_id'];
	// 	}
	// }

	$dealer = Mage::getModel('zgb/dealer')->loadByAdminId($session->getUser()->getId());
	$resource = Mage::getSingleton('core/resource');
	$db = $resource->getConnection('core_read');

	$warehouses = $dealer->getWarehouseIds();
	$orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('warehouse_id', array('in'=>$warehouses));

	$orderIds = array(0);
	foreach($orders as $order)
	{
		$orderIds[] = $order->getId();
	}

	$sql = "select product_id,name,sum(qty_ordered) as qty from sales_flat_order_item as item left join sales_flat_order as o on item.order_id=o.entity_id where 1=1";
	$sql .= " and o.entity_id in (".implode(',', $orderIds).")";
}
else
{
	$sql = "select product_id,name,sum(qty_ordered) as qty from sales_flat_order_item as item left join sales_flat_order as o on item.order_id=o.entity_id where 1=1 ";
}


if($startDate)
{
	$sql .= " and o.created_at>= '{$startDate} 00:00:00'";
}

if($endDate)
{
	$sql .= " and o.created_at<= '{$endDate} 23:59:59'";
}

$sql .= " group by product_id order by qty desc";
$query = $db->query($sql);
$items = $query->fetchAll();

if($items)
{
	$temps = array();
	foreach($items as $item)
	{
		$product = Mage::getModel('catalog/product')->load($item['product_id']);
		$cids = $product->getCategoryIds();
		if(isset($cids)){
			$category = Mage::getModel('catalog/category')->load($cids[0]);
		}
		$temps[] = array('name'=>$item['name'],
			'main_category'=>'全部分类',
			'sub_category'=>$category->getName(),
			'unit'=>$product->getAttributeText('unit'),
			'qty'=>$item['qty']);
		
	}
	$items = $temps;
}

if($zgb->getRoleId('manufacturer')==$roleId && !$ids) $items = array();
?>
<div class="print">
	<div class="report-header">
		<h2>商品销售统计报表（按商品）</h2>
		<div class="search-box">
			<form name="" id="" action="" method="get">
				时间周期：<input type="text" name="start_date" id="start_date" value="<?php echo $startDate;?>" class="laydate-icon"/> 至 <input type="text" name="end_date" id="end_date" value="<?php echo $endDate;?>" class="laydate-icon"/> <input type="submit" value="统计"/>	
			</form>
		</div>
	</div>
	<script type="text/javascript">
		laydate({
		    elem: '#start_date', 
		    event: 'focus'
		});
		laydate({
		    elem: '#end_date', 
		    event: 'focus'
		});
	</script>
	<div class="order-print">
		<table class="data-table">
			<tr>
				<td><b>商品名称</b></td>
				<td width="8%"><b>商品大类</b></td>
				<td width="8%"><b>商品小类</b></td>
				<td width="8%"><b>单位</b></td>
				<td width="8%"><b>数量</b></td>
			</tr>
			<?php foreach($items as $item):?>
			<tr>
				<td><?php echo $item['name']; ?></td>
				<td><?php echo $item['main_category'] ?></td>
				<td><?php echo $item['sub_category'] ?></td>
				<td><?php echo $item['unit']; ?></td>
				<td><?php echo intval($item['qty']); ?></td>
			</tr>
			<?php endforeach;?>
		</table>
	</div>
</div>